package com.huaxiafinance.management.service.impl;

import com.huaxiafinance.management.dto.request.QueryPayOrderDto;
import com.huaxiafinance.management.dto.request.SettlementManageDto;
import com.huaxiafinance.management.exception.BusinessException;
import com.huaxiafinance.management.mapper.MallOrderMapper;
import com.huaxiafinance.management.mapper.MallPayOrderMapper;
import com.huaxiafinance.management.model.MallOrder;
import com.huaxiafinance.management.model.MallPayOrder;
import com.huaxiafinance.management.service.SettlementManageService;
import com.huaxiafinance.management.util.ExportExcelUtil;
import com.huaxiafinance.management.util.MessageResult;
import jxl.write.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * 结算管理接口实现类
 */
@Service("settlementManageService")
public class SettlementManageServiceImpl implements SettlementManageService{
    private static final Logger logger = Logger.getLogger(SettlementManageServiceImpl.class);
    @SuppressWarnings("SpringJavaAutowiringInspection")
    @Autowired
    private MallPayOrderMapper mallPayOrderMapper;

    @Autowired
    private MallOrderMapper mallOrderMapper;

    @Override
    public MessageResult getPayOrderList(QueryPayOrderDto dto) {
        logger.info("查询支付订单列表请求的参数"+dto);
        MessageResult result = new MessageResult();
        try {
            dto.setPage(dto.getPage() == null ? null : (dto.getPage()) * dto.getRows());
            List<MallPayOrder> payOrderList = mallPayOrderMapper.getPayOrderList(dto);
            Integer rows = mallPayOrderMapper.getPayOrderCount(dto);
            result.setSuccessResult();
            result.setData(payOrderList);
            result.setRows(rows);
            logger.info("查询支付订单列表响应的数据"+result.getAsJSON());
            return result;
        }catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        result.setFailureResult();
        return result;

    }

    @Override
    public void updateOrderInfoSettlement(SettlementManageDto dto) throws BusinessException {
        if(dto == null){
            throw new BusinessException("请求参数有误");
        }
        if(dto.getOrderNO() == null || dto.getOrderNO().trim().isEmpty()){
            throw new BusinessException("订单号不能为空");
        }
        if(dto.getPayStatus() == null || ( 2 < dto.getPayStatus() || 0 > dto.getPayStatus())){
            throw new BusinessException("请选择正确的修改状态");
        }
        MallOrder order =mallOrderMapper.selectByOrderNo(dto.getOrderNO());
        if(order == null){
            throw new BusinessException("找不到需要变动的订单");
        }
        if( !Integer.valueOf(1).equals(order.getOrderStatus())){
            throw new BusinessException("需要变动的订单不处于待支付状态，无法变更");
        }

        MallPayOrder payOrder = new MallPayOrder();

        payOrder.setPlatformOrderCode(dto.getPlatformOrderCode());

        payOrder.setTradeOrderNo(dto.getTradeOrderNo());

        payOrder.setPayFlowId(dto.getPayFlowId());

        payOrder.setPayStatus(payOrder.getPayStatus());

        payOrder.setPayMoney(order.getTotalAmount());

        payOrder.setGmtModified(new Date());

        payOrder.setGmtCreate(new Date());

        payOrder.setOrderNo(dto.getOrderNO());

        mallPayOrderMapper.insert(payOrder);

        //支付完成
        if(Integer.valueOf(1).equals(order.getOrderStatus())){

            MallOrder bo = new MallOrder();
            bo.setOrderNo(dto.getOrderNO());
            //支付方式1：支付宝
            bo.setPaymentMode(1);
            //现金支付1 已支付 0未支付
            bo.setPaymentStatus(1);
            //订单状态（1-待支付 2-处理中 3-待发货 4-已发货 5-已完成 6-已取消）
            bo.setOrderStatus(3);
            //支付订单号(支付订单表的platform_order_code字段)
            bo.setPayOrderId(payOrder.getPlatformOrderCode());
            //修改时间
            bo.setGmtModified(new Date());
            mallOrderMapper.updateSettlementByOrderNo(bo);
        }
    }
    /**
     * 时间戳格式化yyyyMMdd
     * @param time
     * @return
     */
    public static String formatDate3(Long time){
        if(time == null || time == 0){
            return "";
        }
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            return df.format(new Date(time));
        } catch (Exception e) {
            return "";
        }

    }
    /**
     * 时间戳格式化yyyyMMdd
     * @param date
     * @return
     */
    public static String formatDate2(Date date){
        if(date == null){
            return "";
        }
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            return df.format(date);
        } catch (Exception e) {
            return "";
        }

    }

    @Override
    public void download(QueryPayOrderDto dto, HttpServletResponse response) {

        dto.setRows(null);
        dto.setPage(null);
        List<MallPayOrder> voList = mallPayOrderMapper.getPayOrderList(dto);

        long nowTime = System.currentTimeMillis();
        WritableWorkbook workbook = ExportExcelUtil.getExcel("结算查询结果_" + formatDate3(nowTime), response);

        /** **********创建工作表************ */
        WritableSheet sheet = ExportExcelUtil.getExcelSheet("结算查询结果", 0,workbook);

        /** ************设置单元格字体************** */

        try {
            WritableCellFormat wcf_center = ExportExcelUtil.getCssCenter();
            WritableCellFormat wcf_left = ExportExcelUtil.getCssNormalAndBorder();

            //序号	支付订单编号	订单编号	用户账号	订单金额	支付时间	支付结果	平台订单号	交易流水号

            sheet.setColumnView(0, 8);
            sheet.setColumnView(1, 18);
            sheet.setColumnView(2, 18);
            sheet.setColumnView(3, 18);
            sheet.setColumnView(4, 18);
            sheet.setColumnView(5, 18);
            sheet.setColumnView(6, 10);
            sheet.setColumnView(7, 36);
            sheet.setColumnView(8, 36);
            sheet.addCell(new Label(0, 0, "序号", wcf_center));
            sheet.addCell(new Label(1, 0, "支付订单编号", wcf_center));
            sheet.addCell(new Label(2, 0, "订单编号", wcf_center));
            sheet.addCell(new Label(3, 0, "用户账号", wcf_center));
            sheet.addCell(new Label(4, 0, "订单金额", wcf_center));
            sheet.addCell(new Label(5, 0, "支付时间", wcf_center));
            sheet.addCell(new Label(6, 0, "支付结果", wcf_center));
            sheet.addCell(new Label(7, 0, "平台订单号", wcf_center));
            sheet.addCell(new Label(8, 0, "交易流水号", wcf_center));


            int i = 1;
            for (MallPayOrder report : voList) {

                sheet.addCell(new Label(0, i, i + "", wcf_left));
                sheet.addCell(new Label(1, i, report.getPayOrderNo()==null?"": report.getPayOrderNo(), wcf_left));
                sheet.addCell(new Label(2, i, report.getOrderNo()==null?"": report.getOrderNo().toString(), wcf_left));
                sheet.addCell(new Label(3, i, report.getCellphone()==null?"": report.getCellphone().toString(), wcf_left));
                sheet.addCell(new Label(4, i, report.getPayMoney()==null?"": report.getPayMoney().toString(), wcf_left));
                sheet.addCell(new Label(5, i, report.getGmtCreate()==null?"": formatDate2(report.getGmtCreate()), wcf_left));
                sheet.addCell(new Label(6, i, report.getStatusName()==null?"": report.getStatusName().toString(), wcf_left));
                sheet.addCell(new Label(7, i, report.getPlatformOrderCode()==null?"": report.getPlatformOrderCode().toString(), wcf_left));
                sheet.addCell(new Label(8, i, report.getPayFlowId()==null?"": report.getPayFlowId().toString(), wcf_left));
                i++;
            }

            /** **********将以上缓存中的内容写到EXCEL文件中******** */
            workbook.write();
            /** *********关闭文件************* */
            workbook.close();
        } catch (WriteException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
